﻿namespace Atomic.Data.AdoNet
{
    using System;
    using System.Data;
    using System.Data.Common;
    using System.Threading.Tasks;

    /// <summary>
    /// 数据提供程序基类。
    /// </summary>
    public abstract partial class DataProviderBase : IDataProvider
    {
        /// <summary>
        /// 查询数据。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>数据读取器。</returns>
        public async Task<DbDataReader> SqlQueryAsync(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            return await this.ExecuteReaderAsync(ConnectionString, commandType, sql, commandParameters);
        }

        /// <summary>
        /// 查询单条数据。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>查询结果。</returns>
        public async Task<object> SingleAsync(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0)
            {
                throw new ArgumentNullException("ConnectionString");
            }

            // 创建并打开数据库连接对象,操作完成释放对象.
            using (DbConnection connection = this.GetDbProviderFactory().CreateConnection())
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                // 调用指定数据库连接字符串重载方法.
                return await ExecuteScalarAsync(connection, null, commandType, sql, commandParameters);
            }
        }

        /// <summary>
        /// 执行 SQL 命令。
        /// </summary>
        /// <param name="commandType">命令类型。</param>
        /// <param name="sql">SQL 语句或者存储过程名称。</param>
        /// <param name="commandParameters">SQL 参数。</param>
        /// <returns>影响行数。</returns>
        public async Task<int> ExecuteSqlCommandAsync(CommandType commandType, string sql, params IDataParameter[] commandParameters)
        {
            if (ConnectionString == null || ConnectionString.Length == 0)
                throw new ArgumentNullException("ConnectionString");

            using (DbConnection connection = this.GetDbProviderFactory().CreateConnection())
            {
                connection.ConnectionString = ConnectionString;
                connection.Open();

                return await ExecuteNonQueryAsync(connection, null, commandType, sql, commandParameters);
            }
        }

        #region ExecuteNonQuery

        /// <summary>
        /// 执行指定数据库连接对象的命令
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new IDataParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param>
        /// <param name="commandText">T存储过程名称或SQL语句</param>
        /// <param name="commandParameters">SqlParamter参数数组</param>
        /// <returns>返回影响的行数</returns>
        protected virtual async Task<int> ExecuteNonQueryAsync(
            DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            // 创建DbCommand命令,并进行预处理
            DbCommand cmd = this.GetDbProviderFactory().CreateCommand();
            cmd.CommandTimeout = 600;
            bool mustCloseConnection = false;
            PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

            // Finally, execute the command
            int retval = await cmd.ExecuteNonQueryAsync();

            // 清除参数,以便再次使用.
            cmd.Parameters.Clear();

            if (mustCloseConnection)
            {
                cmd.Dispose();
                connection.Close();
            }
            return retval;
        }

        #endregion

        #region ExecuteScalar

        /// <summary>
        /// 执行指定数据库连接对象的命令,指定参数,返回结果集中的第一行第一列.
        /// </summary>
        /// <remarks>
        /// 示例:  
        ///  int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new IDataParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名称或SQL语句</param>
        /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param>
        /// <returns>返回结果集中的第一行第一列</returns>
        protected virtual async Task<object> ExecuteScalarAsync(DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            object retval = null;

            try
            {
                // 创建DbCommand命令,并进行预处理
                DbCommand cmd = this.GetDbProviderFactory().CreateCommand();

                bool mustCloseConnection = false;
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

                // 执行DbCommand命令,并返回结果.
                retval = await cmd.ExecuteScalarAsync();

                // 清除参数,以便再次使用.
                cmd.Parameters.Clear();

                if (mustCloseConnection)
                    connection.Close();
            }
            catch
            {
                if (connection != null)
                {
                    connection.Close();
                }
                throw;
            }

            return retval;
        }

        #endregion

        #region ExecuteReader

        /// <summary>
        /// 执行指定数据库连接对象的数据阅读器.
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或 SQL 语句</param>
        /// <param name="commandParameters">IDataParameters 参数数组, 如果没有参数则为 'null'</param>
        /// <returns>返回包含结果集的 IDataReader</returns>
        protected virtual async Task<DbDataReader> ExecuteReaderAsync(string connectionString, CommandType commandType, string commandText, params IDataParameter[] commandParameters)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("ConnectionString");

            DbConnection connection = null;

            try
            {
                connection = this.GetDbProviderFactory().CreateConnection();
                connection.ConnectionString = connectionString;
                connection.Open();

                return await ExecuteReaderAsync(connection, null, commandType, commandText, commandParameters, DbConnectionOwnership.Internal);
            }
            catch
            {
                // If we fail to return the SqlDatReader, we need to close the connection ourselves
                if (connection != null)
                {
                    connection.Close();
                }
                throw;
            }
        }

        /// <summary>
        /// 执行指定数据库连接对象的数据阅读器.
        /// </summary>
        /// <remarks>
        /// 如果是BaseDbHelper打开连接,当连接关闭DataReader也将关闭.
        /// 如果是调用都打开连接,DataReader由调用都管理.
        /// </remarks>
        /// <param name="connection">一个有效的数据库连接对象</param>
        /// <param name="transaction">一个有效的事务,或者为 'null'</param>
        /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param>
        /// <param name="commandText">存储过程名或 SQL 语句</param>
        /// <param name="commandParameters">IDataParameters参数数组,如果没有参数则为'null'</param>
        /// <param name="connectionOwnership">标识数据库连接对象是由调用者提供还是由BaseDbHelper提供</param>
        /// <returns>返回包含结果集的DbDataReader</returns>
        protected virtual async Task<DbDataReader> ExecuteReaderAsync(DbConnection connection, DbTransaction transaction, CommandType commandType, string commandText, IDataParameter[] commandParameters, DbConnectionOwnership connectionOwnership)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");

            bool mustCloseConnection = false;
            // 创建命令
            DbCommand cmd = this.GetDbProviderFactory().CreateCommand();
            cmd.CommandTimeout = 180;
            try
            {
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection);

                // 创建数据阅读器
                DbDataReader dataReader;

                if (connectionOwnership == DbConnectionOwnership.External)
                {
                    dataReader = await cmd.ExecuteReaderAsync();
                }
                else
                {
                    dataReader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
                }

                bool canClear = true;
                foreach (IDataParameter commandParameter in cmd.Parameters)
                {
                    if (commandParameter.Direction != ParameterDirection.Input)
                        canClear = false;
                }

                if (canClear)
                {
                    //cmd.Dispose();
                    cmd.Parameters.Clear();
                }

                return dataReader;
            }
            catch
            {
                if (mustCloseConnection)
                    connection.Close();
                throw;
            }
        }

        #endregion
    }
}